﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.PM
{
    public partial class ProductOrderAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        #region 生产订单逻辑
        /// <summary>
        /// 获取生产订单信息
        /// </summary>
        public void GetProductOrderList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
                if (listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
            }
            Expression<Func<View_PM_ProductOrder, bool>> exp = SearchExpression.FindByGroup<View_PM_ProductOrder>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_PM_ProductOrderDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_PM_ProductOrderDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 通过ID获取生产订单信息
        /// </summary>
        public void GetProductOrderByID()
        {
            //根据生产订单ID获取
            if (Request["id"] != null)
            {
                int code = Commons.String2Int32(Request["id"]);
                var list = DALSession.Current.View_PM_ProductOrderDAL.GetListBy(c => c.ID == code).FirstOrDefault();
                Response.Write(JsonHelper.toJson(list));
            }
            //根据报价单ID获取相关信息
            if (Request["quotID"] != null)
            {
                int quotID = Commons.String2Int32(Request["quotID"]);
                var perQuot = DALSession.Current.View_CM_QuotationDAL.GetListBy(c => c.ID == quotID).FirstOrDefault();
                if (perQuot == null) return;
                View_PM_ProductOrder pernew = new View_PM_ProductOrder();
                pernew.QuotationCode = perQuot.Code;
                pernew.ContractCode = perQuot.ContractCode;
                pernew.ContractID = perQuot.ContractID;
                //pernew.InvoiceAddress = perQuot.InvoiceAddress;
                //pernew.ReceiveAddress = perQuot.ReceiveAddress;
                pernew.OrderDate = DateTime.Now.ToString("yyyy-MM-dd");
                pernew.ReleaseDate = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
                pernew.CustomerName = perQuot.ComName;
                //pernew.SupplierName = perQuot.SupplierName;
                pernew.FillPerson = OperateContext.SessBasicInfo.UserInfo.Name.ToString();
                pernew.FillDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Response.Write(JsonHelper.toJson(pernew));
            }
        }

        /// <summary>
        /// 修改生产订单信息
        /// </summary>
        public void EditProductOrder()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            PM_ProductOrder perNew = DALSession.Current.PM_ProductOrderDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            DALSession.Current.PM_ProductOrderDAL.ModifyAllModel(perNew);
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 添加生产订单信息
        /// </summary>
        public void AddProductOrder()
        {
            string data = Request.Form["data"];
            PM_ProductOrder per = new PM_ProductOrder();
            ModelTools.Form2EditModel(Request.Form, per);
            per.FillDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //完成状态默认未完成，该状态由发货单控制，全部发货完成则更新为已完成
            per.IsComplete = "0";
            //将合同号、报价单ID、报价单号、供应商ID、客户ID、收货地址、收发票地址带到生产订单
            CM_Quotation perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ID == per.QuotationID).FirstOrDefault();
            per.ContractCode = perQuot.ContractCode;
            per.ContractID = perQuot.ContractID;
            per.QuotationCode = perQuot.Code;
            per.SupplierID = perQuot.SupplierID;
            per.CustomerID = perQuot.CustomerID;
            //per.InvoiceAddress = perQuot.InvoiceAddress;
            //per.ReceiveAddress = perQuot.ReceiveAddress;
            //更新报价单和订单状态
            if (perQuot.State == "0") per.State = perQuot.State = "2"; //如果是报价单状态，更新为已订单
            else if (perQuot.State == "1") per.State = perQuot.State = "3"; //如果是已合同状态，更新为已合同已订单
            //生成流水号 SCyyMMdd0002
            string newId = "SC";
            string time = DateTime.Now.ToString("yyMMdd");
            var con = DALSession.Current.PM_ProductOrderDAL.GetListBy(c => c.Code.Substring(2, 6) == time, p => p.Code, false).FirstOrDefault();
            if (con == null)
            {
                newId += time + "0001";
            }
            else
            {
                newId += time + (Commons.String2Int32(con.Code.Substring(8, 4)) + 1).ToString().PadLeft(4, '0');
            }
            per.Code = newId;
            //添加生产订单
            DALSession.Current.PM_ProductOrderDAL.Add(per);
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            //更新报价单
            DALSession.Current.CM_QuotationDAL.ModifyBy(perQuot, p => p.ID == per.QuotationID, "State");
            DALSession.Current.CM_QuotationDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 删除生产订单信息
        /// </summary>
        public void DelProductOrder()
        {
            if (Request.Form["ID"] == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "删除失败"));
                return;
            }
            int Id = Convert.ToInt32(Request.Form["ID"].ToString());
            //计算是否已经有投产的气瓶，如果已有投产则不能删除
            var per = DALSession.Current.View_PM_ProductOrderDAL.GetListBy(p => p.ID == Id).FirstOrDefault();
            int sumUsed =(int) (per.InMakingNum + per.CompletedNum + per.QulifiedNum + per.UnQulifiedNum + per.StorageNum + per.DeliveredNum);
            if (sumUsed > 0)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "该生产订单已投产，无法删除！"));
                return;
            }
            DALSession.Current.PM_ProductOrderDAL.DelBy(p => p.ID == Id);
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();

            int quotID = Convert.ToInt32(Request.Form["QuotationID"].ToString());
            CM_Quotation perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ID == quotID).FirstOrDefault();
            //更新报价单和订单状态
            if (perQuot.State == "2") perQuot.State = "0"; //如果是已订单状态，更新为报价单
            else if (perQuot.State == "3") perQuot.State = "1"; //如果是已合同已订单状态，更新为已合同
            //更新报价单
            DALSession.Current.CM_QuotationDAL.ModifyAllModel(perQuot);
            DALSession.Current.CM_QuotationDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 通过生产订单的生产进度来更新生产订单是否完成的状态,以气瓶全部分析合格为完成标准
        /// </summary>
        /// <param name="productOrderID">生产订单ID</param>
        /// <returns></returns>
        public static bool SetProductOrderIsComplete(int productOrderID)
        {
            var per = DALSession.Current.View_PM_ProductOrderDAL.GetListBy(p => p.ID == productOrderID).FirstOrDefault();
            if (per == null) return false;
            var perProd = DALSession.Current.PM_ProductOrderDAL.GetListBy(p => p.ID == productOrderID).FirstOrDefault();
            //合格数、入库数与发货数之和与订货数相等，都可视为订单生产完成
            if (per.OrderNum == per.QulifiedNum + per.StorageNum + per.DeliveredNum)
            {
                //0未完成 1 已完成 如果已经是订单完成状态，则不进行更新
                if (per.IsComplete == "0")
                {
                    perProd.IsComplete = "1";
                    perProd.CompleteDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    DALSession.Current.PM_ProductOrderDAL.ModifyBy(perProd, p => p.ID == perProd.ID, "IsComplete", "CompleteDate");
                    DALSession.Current.PM_ProductOrderDAL.SaveChanges();
                }
            } //如果小于，则未完成
            else if (per.OrderNum > per.QulifiedNum + per.StorageNum + per.DeliveredNum)
            {
                //默认状态就是未完成，只有对已完成的订单进行反审时才有可能重置为未完成
                if (per.IsComplete == "1")
                {
                    perProd.IsComplete = "0";
                    perProd.CompleteDate = null;
                    DALSession.Current.PM_ProductOrderDAL.ModifyBy(perProd, p => p.ID == perProd.ID, "IsComplete", "CompleteDate");
                    DALSession.Current.PM_ProductOrderDAL.SaveChanges();
                }
            }
            return true;
        }
        #endregion

        #region 气瓶投产相关逻辑
        /// <summary>
        /// 获取气瓶投产信息
        /// </summary>
        public void GetBottleCommissionList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endOrderDate").FirstOrDefault().Field = "OrderDate";
                }
                if (listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
                if (listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endReleaseDate").FirstOrDefault().Field = "ReleaseDate";
                }
            }
            Expression<Func<View_PM_BottleCommission, bool>> exp = SearchExpression.FindByGroup<View_PM_BottleCommission>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_PM_BottleCommissionDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_PM_BottleCommissionDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 判断气瓶绑定时是否有足够的数量用于投产
        /// </summary>
        public void CheckCommissionValid()
        {
            if (Request.Form["detailID"] != null)
            {
                int detailID = Convert.ToInt32(Request.Form["detailID"]);
                var per = DALSession.Current.View_PM_BottleCommissionDAL.GetListBy(p => p.QuotationDetailID == detailID).FirstOrDefault();
                int sumUsed = per.InMakingCount + per.CompletedCount + per.QulifiedCount + per.StorageCount + per.DeliveredCount;
                //如果超过，则不允许继续投产
                if (sumUsed >= per.OrderCount)
                {
                    Response.Write(JsonHelper.toJson(false));
                }
                else
                {
                    Response.Write(JsonHelper.toJson(true));
                }
            }
        }

        #endregion

    }
}